package org.home.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by nanshouxiao on 2017/7/31 10:52.
 */
public class FileUtils {
    public static void writeByteToFile(String filePath, byte[] bytes, boolean isAppend) {
        FileOutputStream fileOutputStream = null;
        byte[] buffer = new byte[1024];
        try {
            fileOutputStream = new FileOutputStream(filePath, isAppend);
            fileOutputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null)
                    fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void writeByteToFile(String filePath, InputStream inputStream, boolean isAppend) {
        FileOutputStream fileOutputStream = null;
        byte[] buffer = new byte[1024];
        try {
            fileOutputStream = new FileOutputStream(filePath, isAppend);
            int readLength = 0;
            if((readLength = inputStream.read(buffer)) > 0){
                fileOutputStream.write(buffer, 0, readLength);
            }
            fileOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null)
                    fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        String str = "这是一行 \n";
        String filepath = "d:/test1.txt";
        writeByteToFile(filepath, str.getBytes(),true);

    }
}
